﻿
using IntelligentEscalator.DLL;
using IntelligentEscalator.Tools;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Timer = System.Timers.Timer;

namespace IntelligentEscalator.Helper
{
    public class DeviceHelper : IHostedService
    {
        private bool isConnected = false; // 设备连接状态
        private Dictionary<string,string> keyValuePairs = new Dictionary<string,string>();// 保存设备
        public Task StartAsync(CancellationToken cancellationToken)
        {

            Timer timer = new Timer(5000);
            timer.Elapsed += timer_Elapsed;
            timer.Start();
            return Task.CompletedTask;
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (!isConnected)
            {
                libdaq2.libdaq2_init();
                int count = libdaq2.libdaq2_device_get_count();
                Console.WriteLine($"设备数量:{count}");
                if (count == 0)
                {
                    isConnected = false;
                }
                else
                {
                    isConnected = true;
                    for (int i = 0; i < count; i++)
                    {
                        string device_sn = libdaq2.libdaq2_device_get_sn((uint)i);
                        Task.Run(() =>
                        {
                            libdaqHelper libdaqHelper = new libdaqHelper();
                            libdaqHelper.StartTimer(device_sn);
                        });

                    }
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }
    }
}
